package com.ssm.dao.impl;

import com.ssm.bean.User;
import com.ssm.dao.IUserDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements IUserDao {

    private SqlSessionFactory factory;

    public UserDaoImpl(SqlSessionFactory factory) {
        this.factory = factory;
    }

    public void setFactory(SqlSessionFactory factory) {
        this.factory = factory;
    }

    public List<User> findAll() {
        //1.根据factory获取SqlSession对象
        SqlSession session = factory.openSession();
        //2.调用SqlSession中的方法，实现查询列表
        List<User> users = session.selectList("com.ssm.dao.IUserDao.findAll");
        //3.释放资源
        session.close();
        return users;
    }

    public void saveUser(User user) {
        SqlSession session = factory.openSession();

        session.insert("com.ssm.dao.IUserDao.saveUser",user);
        session.commit();

    }

    public void updateUser(User user) {

        SqlSession session = factory.openSession();

        session.update("com.ssm.dao.IUserDao.updateUser",user);
        session.commit();


    }

    public void deleteUser(Integer id) {

        SqlSession session = factory.openSession();

        session.delete("com.ssm.dao.IUserDao.deleteUser",id);
        session.commit();

    }

    public User getUserById(Integer id) {
        //1.根据factory获取SqlSession对象
        SqlSession session = factory.openSession();
        //2.调用SqlSession中的方法，实现查询列表
        User users = session.selectOne("com.ssm.dao.IUserDao.getUserById",id);
        //3.释放资源
        session.close();
        return users;
    }

    public List<User> getUserByUsername(String username) {
        //1.根据factory获取SqlSession对象
        SqlSession session = factory.openSession();
        //2.调用SqlSession中的方法，实现查询列表
        List<User> users = session.selectList("com.ssm.dao.IUserDao.getUserByUsername",username);
        //3.释放资源
        session.close();
        return users;
    }

    public int getIntById() {
        //1.根据factory获取SqlSession对象
        SqlSession session = factory.openSession();
        //2.调用SqlSession中的方法，实现查询列表
        int i = session.selectOne("com.ssm.dao.IUserDao.getIntById");
        //3.释放资源
        session.close();
        return i;
    }
}
